#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/10 18:36
    Desc  :
--------------------------------------
"""
import datetime

import jwt

from config.base import SECRET_KEY

secret = SECRET_KEY


def generate_jwt(payload):
    """
    生成jwt
    :param payload: dict 载荷
    :param expiry: datetime 有效期
    :param secret: 密钥
    :return: jwt
    """
    expiry = datetime.datetime.now() + datetime.timedelta(days = 7)
    _payload = {'exp': expiry}
    _payload.update(payload)

    token = jwt.encode(_payload, secret, algorithm = 'HS256')
    return token.decode()


def verify_jwt(token):
    """
    检验jwt
    :param token: jwt
    :param secret: 密钥
    :return: dict: payload
    """

    try:
        payload = jwt.decode(token, secret, algorithm = ['HS256'])
    except jwt.PyJWTError:
        payload = None

    return payload
